package com.medical.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.system.mapper.SysUserRoleMapper;
import com.medical.system.model.entity.SysUserRole;
import com.medical.system.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Override
    public boolean saveUserRoles(Long userId, List<Long> roleIds) {
        //获取用户角色ID集合
        List<Long> userRoleIds = list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, userId))
                .stream().map(item -> item.getRoleId())
                .collect(Collectors.toList());
        //新增用户角色
        List<Long> saveRoleIds;
        if (CollectionUtil.isEmpty(roleIds)) {
            saveRoleIds = roleIds;
        } else {
            saveRoleIds = roleIds.stream().filter(roleId -> !userRoleIds.contains(roleId))
                    .collect(Collectors.toList());;
        }
        List<SysUserRole> saveUserRoles = saveRoleIds.stream().map(roleId -> new SysUserRole(userId, roleId)).collect(Collectors.toList());
        saveBatch(saveUserRoles);
        //删除之前的用户角色
        if (CollectionUtil.isNotEmpty(userRoleIds)) {
            List<Long> removeRoleIds = userRoleIds.stream()
                    .filter(roleId -> !roleIds.contains(roleId))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(removeRoleIds)) {
                remove(new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, userId)
                        .in(SysUserRole::getRoleId, removeRoleIds));
            }
        }
        return false;
    }

    @Override
    public boolean hasAssignedUsers(Long roleId) {
        int count = baseMapper.countUsersForRole(roleId);
        return count > 0;
    }
}
